<template>
  <a-drawer
    :draggable="true"
    :footer="false"
    :ok-loading="loading"
    :title="title"
    :visible="formVisible"
    ok-text="保存"
    unmount-on-close
    width="55%"
    @cancel="handleCancel"
  >
    <a-card :bordered="false">
      <a-row>
        <a-col :flex="1">
          <a-form ref="queryFormRef" :model="queryParams" label-align="left" layout="inline">
            <a-form-item field="userName" label="用户名称">
              <a-input v-model.trim="queryParams.userName" :style="{ width: '200px' }" allow-clear placeholder="请输入用户名称" />
            </a-form-item>
            <a-form-item field="phoneNumber" label="用户手机">
              <a-input
                v-model.trim="queryParams.phoneNumber"
                :style="{ width: '200px' }"
                allow-clear
                placeholder="请输入用户手机"
              />
            </a-form-item>
            <a-form-item>
              <a-space :size="18">
                <a-button type="primary" @click="handleQuery">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="openSelectUser">添加用户</a-button>
            <a-button :disabled="multiple" :loading="cancelAuthUserAllLoading" status="danger" @click="cancelAuthUserAll">
              取消授权
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        v-model:selectedKeys="selectedKeys"
        :bordered="false"
        :columns="cloneColumns as TableColumnData[]"
        :data="userList"
        :default-expand-all-rows="true"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="userId"
        scrollbar
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        @selection-change="onSelectChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.pageNum - 1) * pagination.pageSize }}
        </template>
        <template #userStatus="{ record }">
          <dict-tag :options="sys_normal_disable" :value="record.userStatus" />
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-link
              :hoverable="false"
              :loading="record.userId === cancelAuthUserLoading"
              href="javascript:void(0)"
              @click="cancelAuthUser(record)"
            >
              取消授权
            </a-link>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <select-user ref="selectRef" @ok="handleQuery" />
  </a-drawer>
</template>

<script lang="ts" name="authUser" setup>
import { propTypes } from "@/utils/propTypes";
import useLoading from "@/hooks/useLoading";
import { TableColumnData } from "@arco-design/web-vue/es/table/interface";
import cloneDeep from "lodash/cloneDeep";
import { UserQuery, UserVO } from "@/api/system/user/types";
import { allocatedUserList, authUserCancel, authUserCancelAll } from "@/api/system/role";
import SelectUser from "@/views/system/role/components/select-user.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict("sys_normal_disable"));
const cancelAuthUserLoading = ref<string | number>();
const route = useRoute();
const multiple = ref(true);
const single = ref(true);
const dataFormRef = ref<ArcoFormInstance>();
const selectRef = ref<InstanceType<typeof SelectUser>>();
const queryFormRef = ref<ArcoFormInstance>();
const showColumns = ref<Column[]>([]);
const columns = computed<TableColumnData[]>(() => [
  {
    title: "用户编码",
    dataIndex: "userId",
    slotName: "index",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "用户名称",
    dataIndex: "userName",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "用户昵称",
    dataIndex: "nickName",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "邮箱",
    dataIndex: "email",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "手机",
    dataIndex: "phoneNumber",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "状态",
    dataIndex: "userStatus",
    slotName: "userStatus",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    ellipsis: true,
    tooltip: true,
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "operations",
    slotName: "operations",
    align: "center"
  }
]);

type Column = TableColumnData & { checked?: true };
const formVisible = ref<boolean>(false);
const cancelAuthUserAllLoading = ref<boolean>(false);
const { loading, setLoading } = useLoading(true);
const selectedKeys = ref<Array<number | string>>([]);
const userList = ref<UserVO[]>([]);

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false
});

const cloneColumns = ref<Column[]>([]);
const props = defineProps({
  title: propTypes.string.def("")
});

const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  userName: undefined,
  phoneNumber: undefined
});

const pagination = ref({
  pageNum: queryParams.pageNum,
  pageSize: queryParams.pageSize,
  total: 0,
  showTotal: true,
  showPageSize: true
});

const handleCancel = () => {
  formVisible.value = false;
};

const show = async (roleId: number | string) => {
  queryParams.roleId = roleId;
  await getList();
};

const getList = async () => {
  userList.value = [];
  formVisible.value = true;
  setLoading(true);
  try {
    const res = await allocatedUserList(queryParams);
    userList.value = res.rows;
    pagination.value.total = res.total;
  } finally {
    setLoading(false);
  }
};

/** 表单重置 */
const reset = () => {
  dataFormRef.value?.resetFields();
};

/** 新增按钮操作 */
const openSelectUser = () => {
  reset();
  selectRef.value?.show(queryParams?.roleId);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const onPageChange = async (page: number) => {
  queryParams.pageNum = page;
  await getList();
};

const onPageSizeChange = (pageSize: number) => {
  queryParams.pageSize = pageSize;
  getList();
};

const onSelectChange = (rowKeys: (string | number)[]) => {
  multiple.value = !rowKeys.length;
  single.value = rowKeys.length !== 1;
  selectedKeys.value = rowKeys;
};

/** 删除按钮操作 */
const cancelAuthUser = async (row?: UserVO) => {
  cancelAuthUserLoading.value = row?.userId;
  try {
    await authUserCancel({ userId: row?.userId, roleId: queryParams.roleId });
    await getList();
  } finally {
    cancelAuthUserLoading.value = "";
  }
};

/** 批量取消授权按钮操作 */
const cancelAuthUserAll = async () => {
  cancelAuthUserAllLoading.value = true;
  try {
    const roleId = queryParams.roleId;
    const uIds = selectedKeys.value.join(",");
    await authUserCancelAll({ roleId: roleId, userIds: uIds });
    await getList();
  } finally {
    cancelAuthUserAllLoading.value = false;
  }
};

watch(
  () => columns.value,
  val => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item, _index) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
  },
  { deep: true, immediate: true }
);

watch(
  () => queryParams.pageNum,
  newPageNum => {
    pagination.value.pageNum = newPageNum;
  }
);

watch(
  () => queryParams.pageSize,
  newPageSize => {
    pagination.value.pageSize = newPageSize;
  }
);

defineExpose({
  show
});
</script>
